var app = getApp()
Page({
  data: {
   status:1,
   page: 0,
   showLoading: true,
   noMoretip: false,
   isShowModal:false,
   buyNumber: 1,
   chooseGuige: {
   },
   hours: '00',
   minutes: '00',
   seconds: '00'
  },
  onLoad: function (e) {
    var that = this;
    if(e&&e.tid){
      that.setData({
        tid: e.tid
      })
    }
    if (e && e.actid) {
      that.setData({
        actid: e.actid
      })
    }
    if (e && e.goodid) {
      that.setData({
        goodid: e.goodid
      })
    }
    if (e && e.enterfrom) {
      var enterfrom = e.enterfrom == 'share' ? true : false;
      that.setData({
        enterfrom: enterfrom
      })
    }
    if (!app.globalData.plumSession) {
      app.wechatSq(that);
    } else {
      that.getSlient();
      that.resultData();
      that.requestIndex();
    }
  },
  onShow: function () {
    var that = this;
    that.setData({
      slient: app.globalData.slient ? app.globalData.slient : ''
    });
    if (app.globalData.slient == 1) {
      that.setData({
        isShowgetuser: true
      })
    }
  },
  initPage: function(){
    var that = this;
    that.onLoad();
    that.onShow();
  },
  getSlient:function(){
    var that = this;
    var slient = app.globalData.slient ? app.globalData.slient:'';
    that.setData({
      slient: slient
    })
    if (slient == 1) {
      wx.hideTabBar()
    }
  },
  hideGetuser: function () {
    var that = this;
    that.setData({
      isShowgetuser: false
    })
  },
  // 获取用户信息
  getuserInfo: function (e) {
    var that = this;
    if (e.detail.userInfo) {
      var userdata = e.detail;
      console.log(userdata);
      var slient = that.data.slient;
      var again = false;
      if (slient == 0) {
        again = true;
      }
      app.getuserInfo(that, userdata, again);
    }
  },
  resultData: function () {
    var that = this;
    var tid = that.data.tid;
    console.log('123')
    console.log(tid);
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_mall_group_join',
        tid: tid
      },
      success: function (res) {
        if (res.data.ec == 200) {
          // console.log(res.data);
          console.log(res.data.data);
          // console.log(res.data.data.group_desc.state);
          that.time(res.data.data.over_time);
          that.djs(res.data.data.over_time);
          /** 规格库存判断开始 **/
          if (res.data.data.formatList && res.data.data.formatList.length == 1) {
            for (let i in res.data.data.formatList[0].value) {
              if (res.data.data.formatValueNew[res.data.data.formatList[0].value[i].name].stock == 0) {
                res.data.data.formatList[0].value[i].noCheck = true;
              }
            }
          }
          that.setData({
            resultData: res.data.data,
            tapTime: res.data.data.over_time,
            share: res.data.data.share,
            chooseGuige: {
              stock: res.data.data.group.stock
            }
          })
          // app.errorTip(that, res.data.data.msg, 2000);
        } else {
          console.log(res.data.em);
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        wx.hideToast();
      }
    });
  },
  requestIndex: function () {
    var that = this;
    var page = that.data.page;
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 10000
    });
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_mall_group_list',
        suid: app.globalData.suid,
        type: 0,
        page: page,
      },
      success: function (res) {
        console.log(res.data.data);
        if (res.data.ec == 200) {
          // var shopname = res.data.data.name;
          var allArr = [];
          var initArr = that.data.shopGoods;
          var curArr = res.data.data.goods;
          var lastPageLength = curArr.length;
          if (page > 0) {
            allArr = initArr.concat(curArr);
          } else {
            allArr = res.data.data.goods;
          }
          that.setData({
            shopGoods: allArr
          })
          if (lastPageLength < 10) {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
          // console.log(that.data);
          // wx.setStorage({
          //   key: "goodslistInfor",
          //   data: that.data.shopGoods,
          //   success: function (e) {
          //     console.log("存储成功")
          //   }
          // })
        } else {
          console.log(res.data)
          if (page <= 0) {
            that.setData({
              shopGoods: [],
              showLoading: false
            })
          } else {
            that.setData({
              noMoretip: true,
              showLoading: false
            });
          }
        }
      },
      complete: function () {
        wx.hideToast();
        wx.stopPullDownRefresh();
      }
    });
  },
  onPullDownRefresh: function () {
    this.setData({
      page: 0,
      noMoretip: false,
      showLoading: true
    });
    that.onLoad();
    console.log("下拉刷新");
  },
  onReachBottom: function () {
    var that = this;
    console.log("到达页面底部")
    var isMore = that.data.noMoretip;
    var page = that.data.page;
    page++;
    that.setData({
      page: page
    });
    if (isMore) {
      console.log("已完成或正在加载");
    } else {
      that.onLoad();
    }
  },
  // makeCall: function () {
  //   wx.showModal({
  //     title: '',
  //     content: '联系商家客服 0371-86258375?',
  //     success: function (res) {
  //       if (res.confirm) {
  //         wx.makePhoneCall({
  //           phoneNumber: '0371-86258375',
  //           success: function () {
  //             console.log("拨打电话成功！")
  //           },
  //           fail: function () {
  //             console.log("拨打电话失败！")

  //           }
  //         })
  //       }
  //     }
  //   })
  // },
  goodDetail: function (e) {
    var goodId = e.currentTarget.dataset.id;
    var total = e.currentTarget.dataset.total;
    // var type = e.currentTarget.dataset.type;
    wx.navigateTo({
      url: '/pages/groupGoodDetail/groupGoodDetail?goodid=' + goodId + '&total=' + total
    })
  },
  nowbuy: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    console.log(type)
    that.setData({
      isShowModal: true,
      modalOperaType: "buy",
      type:type

    })
    // wx.navigateTo({
    //   url: '/pages/waitBuyer/waitBuyer',
    // })
  },
  hideModal: function () {
    var that = this;
    that.setData({
      isShowModal: false
    })
  },
  changeNum: function (e) {
    var that = this;
    var type = e.currentTarget.dataset.type;
    var stock = that.data.chooseGuige.stock;
    console.log(stock);

    var buyNum = parseInt(that.data.buyNumber);
    if (type == 'add') {
      if (stock == 0) {
        app.errorTip(that, '商品库存不足', 2000);
        return;
      }
      if (buyNum < stock) {
        buyNum++;
      } else {
        buyNum = stock;
      }
    } else {
      if (buyNum > 1) {
        buyNum--;
      } else {
        buyNum = 1;
      }
    }
    that.setData({
      buyNumber: buyNum
    })
  },
  djs:function(time){
    var that = this;
    var leftTime = time;
    this.data.intervarID = setInterval(function () {
      // var leftTime = (new Date('2017.10.13 18:59:49')) - (new Date()); //计算剩余的毫秒数 
      leftTime--;
      that.time(leftTime);
      // if (leftTime>0){
      //   // var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
      //   var hours = parseInt(leftTime / 60 / 60, 10); //计算剩余的小时 
      //   var minutes = parseInt(leftTime / 60 % 60, 10);//计算剩余的分钟 
      //   var seconds = parseInt(leftTime% 60, 10);//计算剩余的秒数 
      //   // days = days < 10 ? '0' + days : days;
      //   // console.log(days);
      //   hours = hours < 10 ? '0' + hours : hours;
      //   minutes = minutes < 10 ? '0' + minutes : minutes;
      //   seconds = seconds < 10 ? '0' + seconds : seconds;
      //   that.setData({
      //     hours: hours,
      //     minutes: minutes,
      //     seconds: seconds
      //   })
      //   if (hours == '00' && minutes == '00' && seconds == '00') {
      //     clearInterval(that.data.intervarID);
      //     wx.startPullDownRefresh();
      //   }
      // }else{
      //   that.setData({
      //     hours: '00',
      //     minutes: '00',
      //     seconds: '00',
      //   })
      // } 
    }, 1000)
  },
  time: function (leftTime){
    var that = this;
    if (leftTime > 0) {
      // var days = parseInt(leftTime / 1000 / 60 / 60 / 24, 10); //计算剩余的天数 
      var hours = parseInt(leftTime / 60 / 60, 10); //计算剩余的小时 
      var minutes = parseInt(leftTime / 60 % 60, 10);//计算剩余的分钟 
      var seconds = parseInt(leftTime % 60, 10);//计算剩余的秒数 
      // days = days < 10 ? '0' + days : days;
      // console.log(days);
      hours = hours < 10 ? '0' + hours : hours;
      minutes = minutes < 10 ? '0' + minutes : minutes;
      seconds = seconds < 10 ? '0' + seconds : seconds;
      that.setData({
        hours: hours,
        minutes: minutes,
        seconds: seconds
      })
      if (hours == '00' && minutes == '00' && seconds == '00') {
        clearInterval(that.data.intervarID);
        wx.startPullDownRefresh();
      }
    } else {
      that.setData({
        hours: '00',
        minutes: '00',
        seconds: '00',
      })
    } 
  },
  // chooseGuige: function (e) {
  //   var id = e.target.dataset.id;
  //   var price = e.target.dataset.price;
  //   var stock = e.target.dataset.stock;
  //   var name = e.target.dataset.name;
  //   this.setData({
  //     chooseGuige: {
  //       id: id,
  //       price: price,
  //       stock: stock,
  //       name: name
  //     }
  //   })
  // },
  chooseGuige: function (e) {
    var that = this;
    var findex = e.target.dataset.findex;
    var index = e.target.dataset.index;
    var resultData = that.data.resultData;
    if (findex == 0) {
      var curImgformat = resultData.formatList[0].value[index];
      that.setData({
        curImgformat: curImgformat,
      })
    }
    var checkFormat = [];
    for (var i = 0; i < resultData.formatList[findex].value.length; i++) {
      resultData.formatList[findex].value[i].checked = false;
    }
    resultData.formatList[findex].value[index].checked = true;
    for (var i = 0; i < resultData.formatList.length; i++) {
      for (var j = 0; j < resultData.formatList[i].value.length; j++) {
        if (resultData.formatList[i].value[j].checked) {
          checkFormat.push(resultData.formatList[i].value[j]);
        }
      }
    }
    that.setData({
      resultData: resultData,
      checkFormat: checkFormat
    })
    if (checkFormat.length == resultData.formatList.length) {
      var formatName = '';
      for (var i = 0; i < checkFormat.length; i++) {
        formatName += checkFormat[i].name;
      }
      console.log(formatName);
      var chooseGuige = resultData.formatValue[formatName];
      chooseGuige.formatName = formatName;
      chooseGuige.formatName = formatName;
      console.log(chooseGuige);
      that.setData({
        chooseGuige: chooseGuige
      })
    }
  },
  chooseGuige: function (e) {
    var that = this;
    var findex = e.currentTarget.dataset.findex;
    var index = e.currentTarget.dataset.index;
    var disabled = e.currentTarget.dataset.disabled;
    if (disabled) return;
    var resultData = that.data.resultData;
    var checkFormat = [];
    for (var i = 0; i < resultData.formatList[findex].value.length; i++) {
      if (index == i) {
        resultData.formatList[findex].value[index].checked = !resultData.formatList[findex].value[index].checked;
        if (findex == 0 && resultData.formatList[findex].value[index].checked) {
          var curImgformat = resultData.formatList[0].value[index];
          that.setData({
            curImgformat: curImgformat
          })
        } else {
          if (findex == 0) {
            that.setData({
              curImgformat: ''
            })
          }
        }
      } else {
        resultData.formatList[findex].value[i].checked = false;
      }
    }
    for (var i = 0; i < resultData.formatList.length; i++) {
      for (var j = 0; j < resultData.formatList[i].value.length; j++) {
        if (resultData.formatList[i].value[j].checked) {
          checkFormat.push(resultData.formatList[i].value[j]);
        }
      }
    }
    /** 规格库存判断开始 **/
    for (let k in resultData.formatList) {
      for (let n in resultData.formatList[k].value) {
        resultData.formatList[k].value[n].noCheck = false
      }
    }

    for (let i in resultData.formatValueNew) {
      let noStockArr = [];
      let formatValueItem = i.split('-');
      switch (checkFormat.length) {
        case 1:
          if (formatValueItem.indexOf(checkFormat[0].name) != -1 && resultData.formatValueNew[i]['stock'] == 0 && resultData.formatList.length == 2) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            noStockArr = formatValueItem;
          } else if (resultData.formatValueNew[i]['stock'] == 0 && resultData.formatList.length == 1) {
            noStockArr.push(i);
          } else if (formatValueItem.indexOf(checkFormat[0].name) != -1 && resultData.formatValueNew[i]['stock'] == 0 && resultData.formatList.length == 3) {
            noStockArr = [];
          }
          break;
        case 2:
          if ((formatValueItem.indexOf(checkFormat[0].name) != -1 && formatValueItem.indexOf(checkFormat[1].name) != -1) && resultData.formatValueNew[i]['stock'] == 0 && resultData.formatList.length == 3) {
            formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            noStockArr = formatValueItem;
          } else if ((formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1) && resultData.formatValueNew[i]['stock'] == 0 && resultData.formatList.length == 2) {
            if (formatValueItem.indexOf(checkFormat[0].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[0].name)] = '';
            }
            if (formatValueItem.indexOf(checkFormat[1].name) != -1) {
              formatValueItem[formatValueItem.indexOf(checkFormat[1].name)] = '';
            }
            noStockArr = formatValueItem;
          }
          // console.log(noStockArr);
          break;
        case 3:
          if (resultData.formatValueNew[i]['stock'] == 0 && (formatValueItem.indexOf(checkFormat[0].name) != -1 || formatValueItem.indexOf(checkFormat[1].name) != -1 || formatValueItem.indexOf(checkFormat[2].name) != -1)) {
            for (let q in checkFormat) {
              formatValueItem[formatValueItem.indexOf(checkFormat[q].name)] = '';
            }
            if (formatValueItem[0] === '') {
              formatValueItem[1] = formatValueItem[2] = formatValueItem[1] + formatValueItem[2]
            }
            if (formatValueItem[1] === '') {
              formatValueItem[0] = formatValueItem[2] = formatValueItem[0] + formatValueItem[2]
            }
            if (formatValueItem[2] === '') {
              formatValueItem[0] = formatValueItem[1] = formatValueItem[0] + formatValueItem[1]
            }
            console.log(formatValueItem);
            noStockArr = formatValueItem
          }
          break;
      }
      console.log(noStockArr);
      for (let k in resultData.formatList) {
        for (let n in resultData.formatList[k].value) {
          if (noStockArr.indexOf(resultData.formatList[k].value[n].name) != -1) {
            resultData.formatList[k].value[n].noCheck = true
          }
        }
      }
    }
    // 单规格库存判断
    if (resultData.formatList.length == 1) {
      for (let i in resultData.formatList[0].value) {
        if (resultData.formatValueNew[resultData.formatList[0].value[i].name].stock == 0) {
          resultData.formatList[0].value[i].noCheck = true;
        }
      }
    }
    /** 规格库存判断结束 **/
    console.log(resultData.formatList);
    that.setData({
      resultData: resultData,
      checkFormat: checkFormat
    })
    if (checkFormat.length == resultData.formatList.length) {
      var formatName = '';
      for (var i = 0; i < checkFormat.length; i++) {
        formatName += checkFormat[i].name;
        if (i < checkFormat.length - 1) {
          formatName += '-';
        }
      }
      console.log(formatName);
      console.log(resultData.formatValueNew);
      var chooseGuige = resultData.formatValueNew[formatName];
      chooseGuige.formatName = formatName;
      chooseGuige.formatName = formatName;
      console.log(chooseGuige);
      that.setData({
        chooseGuige: chooseGuige
      })
    } else {
      that.setData({
        chooseGuige: {
          stock: resultData.group.stock
        }
      })
    }
  },
  nextStep: function () {
    var that = this;
    // wx.navigateTo({
    //   url: '/pages/waitBuyer/waitBuyer'
    // })
    // console.log(that.data.chooseGuige.id)
    var gfid='';
    if (that.data.chooseGuige.id){
      gfid = that.data.chooseGuige.id;
    }
    var isFormat;
    if (that.data.resultData.format){
      isFormat = that.data.resultData.format.length > 0;
      console.log(isFormat)
    }
    // var gfid = that.data.chooseGuige.id;
    // var isFormat = that.data.goodDetail.format.length > 0;
    var orderArr = [];
    var orderObj = {};
    var extra = {};
    console.log(that.data.actid);
    // extra.type = that.data.type;
    // extra.actid = that.data.actid;
    extra.type = that.data.type;
    extra.actid = that.data.resultData.group.actid;
    extra.gbid = that.data.resultData.group.goId;
    orderObj.gid = that.data.resultData.group.gid;
    console.log(that.data.resultData.group.gid);
    orderObj.gfid = gfid ? gfid:'';
    orderObj.num = that.data.buyNumber;
    orderArr.push(orderObj);
    var data = {};
    data.map ='applet_order_create';
    data.buys = encodeURI(JSON.stringify(orderArr));
    data.extra=extra;
    console.log(app.globalData.requestUrl + '?map=' + data.map + '&suid=' + data.suid + '&buys=' + data.buys);
    console.log(data)
    if (isFormat && !gfid){
      app.errorTip(that, '请选择商品规格！', 2000);
    }else{
      //发起请求，获取列表列表
      wx.showToast({
        title: '加载中',
        icon: 'loading',
        mask: true,
        duration: 10000
      });
      wx.request({
        url: app.globalData.requestUrl,
        data: data,
        success: function (res) {
          if (res.data.ec == 200) {
            console.log(res.data.data);
            wx.setStorage({
              key: "submitOrder",
              data: res.data.data,
              success: function () {
                // wx.navigateTo({
                //   url: '/pages/waitBuyerPay/waitBuyerPay?type='+that.data.type
                // })
                wx.navigateTo({
                  url: '/pages/waitBuyerPay/waitBuyerPay'
                })
              }
            })
          } else {
            wx.showModal({
              title: '提示',
              content: res.data.em,
              showCancel: false
            });
          }
        },
        complete: function () {
          wx.hideToast();
        }
      });
    }
  },
  inviteFriends:function(){
    var that = this;
    that.setData({
      isShowModal: true
    })
  },
  toGroupdetail:function(e){
    var goodid = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/groupGoodDetail/groupGoodDetail?goodid=' + goodid,
    })
  },
  //单张图片预览
  singlePeiviewImg: function (e) {
    var curimg = e.currentTarget.dataset.curimg;
    var imgs = new Array(e.currentTarget.dataset.imgs);
    wx.previewImage({
      current: curimg, // 当前显示图片的http链接
      urls: imgs // 需要预览的图片http链接列表
    })
  },
  onShareAppMessage: function () {
    var that = this;
    var tid = that.data.tid;
    var actid = that.data.actid;
    console.log(actid);
    console.log(tid);
    var title = that.data.share.title;
    var shareInfo = app.globalData.shareInfo;
    title = shareInfo.shareTitle ? shareInfo.shareTitle : title;
    var cover = shareInfo.shareCover ? shareInfo.shareCover : '';
    app.getPoint(that);
    return {
      title: title,
      imageUrl: cover,
      path: '/subpages/joinGroup/joinGroup?enterfrom=share&tid=' + tid,
      imageUrl: that.data.share.img
    }
  },
})